import React from "react";
import ListSelector from "components/list-selector";
import config from "config";
import Chooser from "components/chooser";
import httpFetch from "share/httpFetch";
import ResizeTable from "components/resize-table";
import constants from "share/constants";
import {
  Alert,
  Button,
  Checkbox,
  Col,
  Icon,
  Input,
  InputNumber,
  Modal,
  message,
  Popover,
  Row,
  Radio,
  Select,
  Spin,
  Switch,
  Tooltip,
  Table,
  Upload,
} from "antd";

const Option = Select.Option;

/**
 * @typedef
 * enum FormFieldWidgetType {
 *   0: input // Input输入框
 *   1: inputNumber // InputNumber数字输入框
 *   2: switch // Switch开关
 *   3: select // Select选择框
 *   4：chooser // Modal选择框
 * }
 *
 * @typedef
 * type FormFieldItem = {
 *   columnName: string // 表名
 *   columnComment: string // 表头
 *   widgetType: FormFieldWidgetType // 控件类型
 *   dataSource?: { value: string, label: string } // 数据源，仅当widgetType为select|chooser时可设置
 *   visible: 1 | 0  // 是否显示, 1显示 0不显示
 * }
 */

const EnumFormFieldWidgetType = (() => {
  const inner = [0, 1, 2, 3, 4, 5];
  inner.input = 0;
  inner.inputNumber = 1;
  inner.switch = 2;
  inner.select = 3;
  inner.chooser = 4;
  inner.date = 5;
  return inner;
})();

export default class UnifiedTableConfig extends React.Component {
  constructor(props) {
    super(props);

    const { defaultValue = {} } = props;
    let dataSource = null;
    let dataSourceCode = null;
    let formField = [];
    try {
      dataSource = JSON.parse(defaultValue.dataPool);
      dataSourceCode = dataSource.code;
    } catch (e) {
      if (config.appEnv === "dev") {
        console.error(e);
      }
    }
    try {
      formField = JSON.parse(defaultValue.formField);
    } catch (e) {
      if (config.appEnv === "dev") {
        console.error(e);
      }
    }

    this.state = {
      importFile: defaultValue.importFile || false,
      exportFile: defaultValue.exportFile || false,
      lineEdit: defaultValue.lineEdit || false,
      maxPageSize: defaultValue.maxPageSize || 10,
      dataSource,
      dataSourceCode,
      formField,
    };

    this.columns = [
      {
        title: "字段名",
        width: 120,
        dataIndex: "columnName",
        key: "columnName",
        fixed: "left",
        render: (value, record) => {
          return (
            <Tooltip title={value}>
              <div
                style={{
                  width: 90,
                  fontSize: 12,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {value}
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: "表头",
        key: "columnComment",
        dataIndex: "columnComment",
        render: (value, record) => {
          return (
            <Input
              size="small"
              value={record.columnComment}
              onChange={(e) =>
                this.updateRow({
                  ...record,
                  columnComment: e.target.value,
                })
              }
            ></Input>
          );
        },
      },
      {
        title: "控件类型",
        dataIndex: "widgetType",
        key: "widgetType",
        width: 110,
        render: (value, record) => {
          return (
            <Select
              value={value}
              size="small"
              onChange={(value) => {
                const item = {
                  ...record,
                  widgetType: value,
                };
                if (item.widgetType < 3 || item.widgetType > 4) {
                  delete item.dataSource;
                }
                this.updateRow(item);
              }}
            >
              <Option value={0}>普通文本</Option>
              <Option value={1}>数字</Option>
              <Option value={2}>开关</Option>
              <Option value={3}>选择框</Option>
              <Option value={4}>模态选择框</Option>
              <Option value={5}>日期选择</Option>
            </Select>
          );
        },
      },
      {
        title: "数据源",
        key: "dataSource",
        width: 120,
        dataIndex: "dataSource",
        render: (value, record) => {
          return (
            <Chooser
              selectorItem={{
                key: "code",
                title: "选择数据源",
                columns: [
                  {
                    title: "编码",
                    dataIndex: "code",
                  },
                  { title: "名称", dataIndex: "name" },
                ],
                searchForm: [],
                url: `${config.baseUrl}/api/v2/custom/enumerations`,
              }}
              listExtraParams={{
                isCustom: "CUSTOM",
              }}
              value={value ? [value] : []}
              onChange={(chooserValue) => {
                if (chooserValue.length > 0) {
                  const item = chooserValue[0];
                  const nextDataSource = {
                    name: item.name,
                    code: item.code,
                  };
                  this.updateRow({
                    ...record,
                    dataSource: nextDataSource,
                  });
                }
              }}
              single
              valueKey="code"
              labelKey="name"
              disabled={record.widgetType !== 3 && record.widgetType !== 4}
            />
          );
        },
      },
      {
        key: "visible",
        width: 90,
        title: "是否显示",
        dataIndex: "visible",
        render: (checked, record) => {
          return (
            <Switch
              size="small"
              checked={checked === 1}
              onChange={(checked) => {
                const item = {
                  ...record,
                  visible: checked ? 1 : 0,
                };
                if (item.visible === 0) {
                  delete item.dataSource;
                }
                this.updateRow(item);
              }}
            ></Switch>
          );
        },
      },
    ];
  }

  componentDidMount() {}

  componentDidUpdate(prevProps, prevState) {
    if (this.state.dataSourceCode !== prevState.dataSourceCode) {
      this.updateTableStructure(this.state.dataSourceCode);
    }
  }

  handleShouldSupportImportChange = (value) => {
    this.setState(
      {
        importFile: value,
      },
      () => {
        this.emitChange();
      }
    );
  };

  handleShouldSupportDownloadChange = (value) => {
    this.setState(
      {
        exportFile: value,
      },
      () => {
        this.emitChange();
      }
    );
  };

  handleShouldUseLineEditChange = (value) => {
    this.setState(
      {
        lineEdit: value,
      },
      () => {
        this.emitChange();
      }
    );
  };

  handlePagingLimitChange = (value) => {
    this.setState(
      {
        maxPageSize: value,
      },
      () => {
        this.emitChange();
      }
    );
  };

  handleDataSourceChange = (selected) => {
    if (selected.length === 1) {
      this.setState(
        {
          dataSource: selected[0],
          dataSourceCode: selected[0].code,
        },
        () => {
          this.emitChange();
        }
      );
    }
  };

  updateTableStructure = async (tableName) => {
    try {
      const res = await httpFetch.get(
        `${config.baseUrl}/api/public/assembly/getSchema/${tableName}`
      );
      /**
       * @type FormFieldItem[]
       */
      const formField = res.data.map((item) => ({
        columnComment: item.columnComment,
        columnName: item.columnName,
        widgetType: EnumFormFieldWidgetType.input,
        visible: 1,
      }));
      this.setState(
        {
          formField,
        },
        this.emitChange
      );
    } catch (e) {
      if (config.appEnv === "dev") {
        console.error(e);
      }
      message.error("根据数据源获取表结构失败");
    }
  };

  updateRow = (rowData) => {
    this.setState(
      ({ formField }) => ({
        formField: formField.map((item) => {
          if (item.columnName === rowData.columnName) {
            return rowData;
          }
          return item;
        }),
      }),
      () => {
        this.emitChange();
      }
    );
  };

  emitChange = () => {
    if (this.props.onChange) {
      const formField = this.state.formField.map((item) => {
        if (item.widgetType < 3 || item.widgetType > 4) {
          delete item.dataSource;
        }
        return item;
      });
      this.props.onChange({
        type: constants.getMCDFormTypeCodeByValue(this.context.formType),
        formField: JSON.stringify(formField),
        maxPageSize: this.state.maxPageSize || 10,
        importFile: !!this.state.importFile,
        exportFile: !!this.state.exportFile,
        lineEdit: !!this.state.lineEdit,
        dataPool: JSON.stringify(this.state.dataSource),
      });
    }
  };

  render() {
    const {
      importFile,
      exportFile,
      lineEdit,
      maxPageSize,
      dataSource,
      formField,
    } = this.state;

    const { manuallyUploadTemplate } = this.props;
    const Authorization =
      "Bearer " + JSON.parse(localStorage.getItem("hly.token")).access_token;

    const pkId = this.props.pkId || this.context.formOID;
    const customEnumerationItemOID = dataSource
      ? dataSource.customEnumerationItemOID
      : null;

    return (
      <div>
        <div>
          <div className="widget-setting-title">数据源</div>
          <div
            style={{
              marginTop: -4,
              marginBottom: 8,
              fontSize: 11,
              color: "#999",
            }}
          >
            如果添加多个公共列表，数据源不能重复。
          </div>
          <Chooser
            selectorItem={{
              key: "code",
              title: "选择数据源",
              columns: [
                { title: "名称", dataIndex: "messageKey" },
                // {
                //   title: "编码",
                //   dataIndex: "code",
                // },
              ],
              searchForm: [],
              url: `${config.baseUrl}/api/public/assembly/custom/enumerations/PUBLIC_DATASOURCE`,
            }}
            value={dataSource ? [dataSource] : []}
            onChange={this.handleDataSourceChange}
            single
            valueKey="code"
            labelKey="messageKey"
          />

          <div className="widget-setting-title">字段配置</div>

          <div>
            <Table
              scroll={{ x: 600, y: 500 }}
              columns={this.columns}
              dataSource={formField}
              // onRow={(record) => ({})}
              rowKey={(record) => record.columnName}
              pagination={false}
              loading={false}
              // hideScroll={false}
              // rowClassName="chooser-table-row"
              bordered
              size="small"
              emptyText="请先选择数据源"
            />
          </div>

          <div className="widget-setting-title">
            <span>是否导入: </span>
            <Switch
              onChange={this.handleShouldSupportImportChange}
              checked={importFile}
            />
          </div>
          {importFile && manuallyUploadTemplate && (
            <div>
              {!this.state.dataSource ? (
                <Alert type="warning" message="请先选择数据源"></Alert>
              ) : (
                <div style={{ display: "flex", alignItems: "baseline" }}>
                  <div
                    className="widget-setting-title"
                    style={{ marginRight: 10 }}
                  >
                    <div>上传导入模板</div>
                  </div>
                  <div>
                    <Upload
                      multiple={false}
                      accept=".xls,.xlsx"
                      headers={{
                        Authorization,
                      }}
                      action={`${config.baseUrl}/api/public/assembly/uploadMould/${pkId}/${customEnumerationItemOID}`}
                    >
                      <Button size="small" icon="upload">
                        上传
                      </Button>
                    </Upload>
                    <div style={{ height: 5 }}></div>
                    <div>支持xls/xlsx格式</div>
                  </div>
                </div>
              )}
            </div>
          )}
          <div className="widget-setting-title">
            <span>是否导出: </span>
            <Switch
              onChange={this.handleShouldSupportDownloadChange}
              checked={exportFile}
            />
          </div>

          <div className="widget-setting-title">
            <span>是否使用行编辑: </span>
            <Switch
              onChange={this.handleShouldUseLineEditChange}
              checked={lineEdit}
            />
          </div>

          <div className="widget-setting-title">
            <span>默认显示每页数量</span>
          </div>
          <div style={{ margin: "8px 0" }}>
            <InputNumber
              onChange={this.handlePagingLimitChange}
              value={maxPageSize}
            />
          </div>
        </div>
      </div>
    );
  }
}

UnifiedTableConfig.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  booksID: React.PropTypes.string,
  form: React.PropTypes.object,
  propertyList: React.PropTypes.array,
};
